namespace :bld do
  desc "get data and export"
  task :fans => :environment do
    urlb = "http://interface.bilibili.tv/card/"
    fans = (YAML.load(open(%[#{Rails.root}/config/_fans.yml])) rescue [])
    fans_nil = (YAML.load(open(%[#{Rails.root}/config/_fans_nil.yml])) rescue [])
    fan_names = fans.collect{|fan| fan["name"]}
    wids = WeeklyResult.all(:include => :weekly_result_work, :select => "weekly_result_works.wid", :conditions=> "score_rank < 101").collect{|wr| wr.wid}.uniq
    authors = Work.find_all_by_wid(wids).collect{|w| w.author_name}.uniq
    authors = authors - fan_names - fans_nil
    p au_count = authors.count
    authors.each do |author_name|
      url = urlb + URI.escape(author_name) + ".js"
      begin
        http = Net::HTTP::Persistent.new
        s = http.request(URI.parse(url))
        sh = (JSON.parse s.plain_body[/\{.*\}/] rescue {})
        sleep 0.4
        if sh["mid"]
          puts "#{sh["mid"]}  #{sh["name"]} : attention:#{sh["attention"]}  fans:#{sh["fans"]}"
          fans << sh
        else
          if sh["iscache"] == false
            puts "#{author_name} nil"
            fans_nil << author_name
          end
        end
      rescue
        p $!.class
        fans_nil << author_name if $!.class == URI::InvalidURIError
         break
      end
      p au_count -= 1
    end
    File.open(%[#{Rails.root}/config/_fans.yml],"w"){ |io| YAML.dump fans,io }
    File.open(%[#{Rails.root}/config/_fans_nil.yml],"w"){ |io| YAML.dump fans_nil,io }
  end

  task :fans_stat => :environment do
    fans = (YAML.load(open(%[#{Rails.root}/config/_fans.yml])) rescue [])
    fans.sort_by do |fan|
      fan["fans"]
    end.reverse[0...30].each do |fan|
      puts "#{fan["name"]}  #{fan["fans"]}"
    end
  end
end


